package csc.fresher.finalgroupfour.controller.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import csc.fresher.finalgroupfour.domain.Account;
import csc.fresher.finalgroupfour.domain.Customer;
import csc.fresher.finalgroupfour.domain.Role;
import csc.fresher.finalgroupfour.domain.User;
import csc.fresher.finalgroupfour.service.BankService;

@Controller
public class CreateUserController {
	@Autowired
	private BankService bankService;
	int count = 0;

	public BankService getBankService() {
		return bankService;
	}

	@Autowired
	public void setBankService(BankService bankService) {
		this.bankService = bankService;
	}
	
	/**
	 * @param request
	 * @return
	 * Generate View for createUser action.
	 */
	@RequestMapping(value="/createUserSreen")
	public ModelAndView createUserView(HttpServletRequest request) {
		ModelAndView model = new ModelAndView("createUserSreen");
		
		// Only list customers that doesn't have an user log in account.
		List<Customer> customers = bankService.listAvailableCustomers();
		model.addObject("listCustomer", customers);
		return model;
	}
	
	/**
	 * @param request
	 * @return
	 * Do createUser action.
	 */
	@RequestMapping(value="/createUser")
	public String createUser(HttpServletRequest request) {
		
		// Get parameters from user input.
		String loginId = request.getParameter("loginId");
		String password = request.getParameter("password");
		String userState = request.getParameter("userState");
		String customerCardNumberId = request.getParameter("chosenCustomer");
		
		// Find customer base on cardCustomerId information.
		Customer customer = bankService.findCustomer(customerCardNumberId);
		// Load accounts of above customer
		List<Account> accounts = (List<Account>) customer.getAccounts();
		// Create User instance from user input parameters.
		User user = new User(loginId, password, userState);
		// Set default Role for every new User is ROLE_USER
		List<Role> roles = bankService.listRoles();
		for(Role role : roles) {
			if(role.getRole().equals("ROLE_USER")) {
				user.setRole(role); 
			}
		}
		bankService.addUser(user);
		
		// Set Accounts of Customer for newly created User
		for (Account acc : accounts) {
			acc.setUser(user);
			bankService.updateAccount(acc);
		}
		return "home";
	}
}
